//
//  VideoViewController.m
//  PhoenixNews
//
//  Created by dllo on 16/1/23.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VideoViewController.h"

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height
@interface VideoViewController ()
@property (nonatomic, retain) UIView *playerView;
@property (nonatomic, strong) AVPlayer *player;/**< 播放器对象 */
@property (nonatomic, strong) AVPlayerLayer *playerLayer;/**< 播放图层 */
@property (nonatomic, strong) AVPlayerItem *playerItem;/**< 播放对象 */
@property (nonatomic, assign) BOOL isPlay;/**< 是否播放 */
@property (nonatomic, retain) UIButton *buttonAction;// 开始播放按钮
@property (nonatomic, retain) UIView *bottomView; // 底部放置按钮的View
@property (nonatomic, assign) BOOL isDismiss;/**< 是否隐藏 */
@property (nonatomic, retain) UILabel *timeLable; // 视频时间
@property (nonatomic, retain) UISlider *progress; // 进度条
@property (nonatomic, assign) CGFloat totalDuration;/**< 总时长 */

// 视频播放地址
@property (nonatomic, retain) NSString *ViedoUrl;
// 视频图片
@property (nonatomic, retain) UIImageView *VideoImage;
// 点击视频图片按钮
@property (nonatomic, retain) UIButton *buttonImage;
// 跳转全屏播放页面
@property (nonatomic, retain) UIButton *fullButton;
@end

@implementation VideoViewController
- (void)dealloc {
    [_playerView release];
    [_player release];
    [_playerItem release];
    [_playerLayer release];
    [_buttonAction release];
    [_bottomView release];
    [_timeLable release];
    [_progress release];
    [_ViedoUrl release];
    [_VideoImage release];
    [_fullButton release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"block"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    // 底层VIEW
    self.playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 80, 375, 240)];
    self.playerView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_playerView];
    
    
    self.bottomView =[[UIView alloc] initWithFrame: CGRectMake(0, self.playerView.frame.size.height - 40, self.playerView.frame.size.width , 40)];
    self.bottomView.backgroundColor = [UIColor redColor];
    [self.playerView addSubview:_bottomView];
    [_bottomView release];
    
    
    // 视频时间
    self.timeLable = [[UILabel alloc] initWithFrame:CGRectMake(200, 0, 115, 40)];
    _timeLable.text = @"00:00/00:00";
    [self.bottomView addSubview:_timeLable];
    // 进度条
    self.progress = [[UISlider alloc] initWithFrame:CGRectMake(70, 0, 130, 40)];
    
    self.progress.backgroundColor = [UIColor grayColor];
    [self.progress addTarget:self action:@selector(porgressAction:) forControlEvents:UIControlEventValueChanged];
    [self.bottomView addSubview:_progress];
    [_progress release];
    // 开始按钮
    self.buttonAction = [UIButton buttonWithType:UIButtonTypeCustom];
    _buttonAction.frame = CGRectMake(0, 0, 60, 40);
    [self.buttonAction setTitle:@"暂停" forState: UIControlStateNormal];
    [_buttonAction addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.bottomView addSubview:_buttonAction];
    
    
    // 初始化播放器
    [self createAVPlayer];
    // 播放
    [_player play];
    // 开始播放
    _isPlay = YES;
    // 初始化时间显示
   
    // 初始化进度条
    _progress.value = 0;
    // 添加手势 隐藏边栏
    [self addTapToDismissBar];
    // 通过通知中心监听 播放器/视频/页面 状态信息
    //    [self addNotificationCenter];
    // 进度条监听
    [self progressObserving];
    
    [self addNotificationCenter];
    
    
   
}
// 返回上一页面关闭视频播放
- (void)leftAction:(UIBarButtonItem *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 初始化播放器
- (void)createAVPlayer
{
    // 视频网址
    NSString *str = self.urlStr;
    
    NSURL *url = [NSURL URLWithString:str];
    // 创建播放对象(playerItem)
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    // 创建播放器(player)
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    
    // 创建显示layer(playerLayer)
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
   
    // layer需要设置大小
    _playerLayer.frame = CGRectMake(5, 5, self.view.bounds.size.width - 10, _playerView.frame.size.height - 10);
  
    // 视频填充模式
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    // 将显示的图层 放在页面里显示

    [self.playerView.layer insertSublayer:_playerLayer atIndex:0];
    
    // 点击按钮全屏
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(self.bottomView.frame.size.width - 60, 5, 30, 30);
//    [button setImage:[UIImage imageNamed:@"FullButton"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.bottomView addSubview:button];
}

- (void)progressObserving
{
    // 设置(1, 1) 每秒刷新一次
    // 参数1: 时间监听器刷新时间
    // 参数2: 队列
    // 参数3: 刷新时执行的block
    __weak VideoViewController *vc = self;
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 获取总时长
        CGFloat duration = CMTimeGetSeconds(vc.playerItem.duration);
        // 获取当前时长
        CGFloat current = CMTimeGetSeconds(vc.player.currentTime);
        // 获取倒计时
        CGFloat rem = duration;
        
        // 剩余时间
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d", (int)rem / 60, (int)rem % 60];
        // 当前时间
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];
        // 拼接时间
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentT, totalT];
        vc.timeLable.text = timeStr;
        // 保存总时长 用于slider手动控制进度
        vc.totalDuration = duration;
        // 控制slider的当前进度
        vc.progress.value = current / duration;
    }];
}
#pragma mark - 通知中心
- (void)addNotificationCenter
{
    // 是否播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    // 监听屏幕旋转
    [[NSNotificationCenter defaultCenter] addObserver:(self) selector:@selector(statusBarPositionChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
- (void)moviePlayDidEnd:(NSNotification *)noti
{
    NSLog(@"视频播放已经结束");
}
- (void)statusBarPositionChange:(NSNotification *)noti {
    // 使用代码监听横竖屏
    // 获取状态栏方向
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    // 判读
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"向左横屏");
        [self landscape];
    }else if (orientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"向右横屏");
        [self landscape];
    }else if (orientation == UIInterfaceOrientationMaskPortrait) {
        NSLog(@"竖屏");
        [self protradin];
    }
}

#pragma mark - 横屏设置
- (void)landscape {
    _playerView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    _playerLayer.frame = CGRectMake(5, 5, WIDTH - 10, HEIGHT - 10);
    _bottomView.frame = CGRectMake(0, 285, WIDTH, 40);
    
}

#pragma mark - 竖屏设置
- (void)protradin {
    
    _playerLayer.frame = CGRectMake(5, 5, WIDTH - 10, 230);
    _bottomView.frame = CGRectMake(0, 60, self.view.frame.size.width, 40);
}


#pragma mark - 添加手势
- (void)addTapToDismissBar
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_playerView addGestureRecognizer:tap];
}
#pragma mark - 隐藏边栏
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    // 初始播放 还未隐藏 isDismiss = NO
    // 隐藏
    if (!_isDismiss) {
        // 隐藏边栏
        [UIView animateWithDuration:0.5 animations:^{
            _bottomView.alpha = 0;
        }];
    } else {
        // 显示边栏
        [UIView animateWithDuration:0.5 animations:^{
            _bottomView.alpha = 0.8;
        }];
    }
    _isDismiss = !_isDismiss;
}
#pragma mark - 手动进度控制
- (void)porgressAction:(UISlider *)slider {
        [_player pause];
    // 当前时间
    CGFloat current = slider.value * _totalDuration;
    // 创建CMTime
    CMTime time = CMTimeMake(current, 1);
    // 把time赋值给播放器 跳转到对应的时间点
    [_player seekToTime:time completionHandler:^(BOOL finished) {
        [_player play];
    }];
    
}
#pragma mark 开始/ 暂停
- (void)button:(UIButton *)sender {
    // BOOL判断
    if (_isPlay) {
        // 正在播放时 暂停
       [_player pause];
        [sender setTitle:@"开始" forState:UIControlStateNormal];
    } else {
        
        
        [_player play];
        
        [sender setTitle:@"暂停" forState:UIControlStateNormal];
    }
    _isPlay = !_isPlay;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
